<template>
  <view class="container" style="padding-bottom: 100px" v-if="isLoaded">
    <!-- 表单 -->
    <view class="content" style="padding: 30rpx 30rpx 120rpx; background-color: #fff">
      <li-form>
        <block v-if="id == 1">
          <li-form-item label="礼券编码">
            <li-input v-model="form.couponCode" disabled prop="couponCode" />
          </li-form-item>
          <li-form-item label="礼券名称" :border="false">
            <view style="display: flex">
              <li-input style="flex: 1" v-model="form.couponName" disabled prop="couponId">
                <view
                  style="
                    background-color: #f3c45d;
                    border-left: 1px solid #dadada;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #fff;
                    padding: 0 5px;
                    height: 100%;
                  "
                  v-on:click="onChooseCoupon(1)"
                >
                  选择优惠券
                </view>
              </li-input>
            </view>
          </li-form-item>
          <li-form-item label="礼券类型">
            <li-picker v-model="form.typeId" :rangeList="couponTypeEnum" disabled prop="typeId"></li-picker>
          </li-form-item>
          <li-form-item label="礼券面额">
            <li-input v-model="form.parValue" disabled prop="parValue"></li-input>
          </li-form-item>
          <li-form-item label="	发放时间">
            <li-date-picker v-model="form.distributionDate" />
          </li-form-item>
          <li-form-item label="发放人">
            <li-input v-model="form.createUserName" disabled prop="createUserName" />
          </li-form-item>
          <li-form-item label="开始领取时间">
            <li-date-picker v-model="form.collectionStartDate" />
          </li-form-item>
          <li-form-item label="结束领取时间">
            <li-date-picker v-model="form.collectionEndDate" />
          </li-form-item>
          <li-form-item label="礼券状态">
            <li-picker
              :rangeList="[
                { id: 1, text: '已发放' },
                { id: 2, text: '已使用' },
                { id: 3, text: '已停用' }
              ]"
              v-model="form.status"
              prop="status"
            ></li-picker>
          </li-form-item>
          <li-form-item label="绑定会员">
            <li-input v-model="form.userName" disabled prop="userName">
              <view
                style="
                  background-color: #f3c45d;
                  border-left: 1px solid #dadada;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  color: #fff;
                  padding: 0 5px;
                  height: 100%;
                "
                v-on:click="onChooseCoupon(2)"
              >
                选择会员
              </view>
            </li-input>
          </li-form-item>
          <li-form-item label="备注">
            <li-textarea v-model="form.remark" placeholder="请输入" prop="remark"></li-textarea>
          </li-form-item>
        </block>
        <block v-else>
          <li-form-item label="礼券名称">
            <view style="display: flex">
              <li-input style="flex: 1" v-model="form.couponName" disabled prop="couponId">
                <view
                  style="
                    background-color: #f3c45d;
                    border-left: 1px solid #dadada;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #fff;
                    padding: 0 5px;
                    height: 100%;
                  "
                  v-on:click="onChooseCoupon(1)"
                >
                  选择优惠券
                </view>
              </li-input>
            </view>
          </li-form-item>
          <li-form-item label="起始编码">
            <li-input v-model="form.startCode" prop="startCode" />
          </li-form-item>
          <li-form-item label="首字符">
            <li-input v-model="form.fristChar" prop="fristChar" />
          </li-form-item>
          <li-form-item label="开始领取时间">
            <li-date-picker v-model="form.collectionStartDate" />
          </li-form-item>
          <li-form-item label="发放日期">
            <li-date-picker v-model="form.distributionDate" />
          </li-form-item>
          <li-form-item label="绑定会员">
            <li-input v-model="form.userName" disabled prop="userName">
              <view
                style="
                  background-color: #f3c45d;
                  border-left: 1px solid #dadada;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  color: #fff;
                  padding: 0 5px;
                  height: 100%;
                "
                v-on:click="onChooseCoupon(2)"
              >
                选择会员
              </view>
            </li-input>
          </li-form-item>
          <li-form-item label="制作张数">
            <li-input v-model="form.count" prop="count" rule="int" />
          </li-form-item>
          <li-form-item label="终止编码">
            <li-input v-model="form.endCode" prop="endCode" />
          </li-form-item>
          <li-form-item label="结尾字符">
            <li-input v-model="form.endChar" prop="endChar" />
          </li-form-item>
          <li-form-item label="结束领取时间">
            <li-date-picker v-model="form.collectionEndDate" />
          </li-form-item>
          <li-form-item label="消费密码">
            <li-input v-model="form.password" prop="password" rule="trim" />
          </li-form-item>
        </block>
      </li-form>
    </view>

    <li-bottom-btns :mode="mode" @btnDelClick="btnDelClick" @btnEditOrSaveSubmitClick="btnEditOrSaveSubmitClick" />

    <!-- coupon popup -->
    <li-popup :title="type == 1 ? '选择优惠券' : '选择会员'" :show="showCouponPopup" @close="closeCouponPopup" @open="openCouponPopup">
      <view class="items-container" style="overflow-y: scroll; height: 100%; padding-top: 50px">
        <view class="items" :id="`menu-${item.id}`" v-for="(item, index) in type == 1 ? FoodCouponList : UserList" :key="item.id">
          <text class="item-title" style="flex: 1">{{ item[type == 1 ? 'name' : 'nickName'] }}</text>
          <text style="padding-right: 8px">{{ type == 1 ? couponTypeEnum.find((itm) => itm.id == item['typeId']).text : item.number }}</text>
          <button
            size="mini"
            style="border-radius: 8px; color: #fff"
            v-if="(type == 1 && form.couponId != item.id) || (type == 2 && form.userId != item.id)"
            v-on:click="() => onItemClick(item)"
            :style="{
              'background-color': type == 1 && form.couponId == item.id ? '#f56c6c' : '#f3c45d'
            }"
          >
            {{ form.couponId == item.id ? '取消' : '选择' }}
          </button>
          <button size="mini" style="border-radius: 8px; color: #fff; background-color: #fff; color: #f56c6c; border: 1px solid #f56c6c" v-else>已选</button>
        </view>
      </view>
    </li-popup>
  </view>
</template>
<script>
import liFormMixin from '../../../mixins/liFormMixin';
import { genCouponCode, GetFoodCouponList, AddFoodCouponUser, BatchCreateCouponUser } from '../../../common/modules/catering.js';
import { GetUserList } from '../../../common/api.js';
import { transferTypeEnum, transfer } from '../../../common/dataTransfer.js';
import { utoast, umodal, uNavigateBack, uNavigateTo } from '../../../utils/uniUtils.js';
import checker from '@/common/graceChecker';

import { checkerType, modeEnum, booleanEnum, couponTypeEnum, weekEnumable, dayEnum, cycleTypeEnum, channelTypeEnum } from '../../../constants/normalConstants.js';
import dateUtils from '../../../utils/date.js';
import { toastIconEnum } from '../../../constants/uiConstants.js';

export default {
  mixins: [liFormMixin],
  async onLoad(options) {
    this.id = options.id;
    this.loadEvent(options, this);
  },

  async mounted() {
    let formData =
      this.id == 1
        ? {
            couponCode: '',
            couponId: null,
            couponName: '',
            typeId: '',
            couponId: 0,
            parValue: null,
            distributionDate: dateUtils.getToday(),
            createUserName: null,
            collectionStartDate: dateUtils.getToday(),
            collectionEndDate: '2099-12-31',
            status: 1,
            userName: '',
            remark: ''
          }
        : {
            couponId: 0,
            couponName: '',
            startCode: '',
            fristChar: '',
            collectionStartDate: dateUtils.getToday(),
            distributionDate: dateUtils.getToday(),
            userName: '',
            count: 1,
            endCode: '',
            endChar: '',
            collectionEndDate: '2099-12-31',
            password: '',
            remark: ''
          };
    this.mountedEvent(this, formData);
  },
  data: function () {
    return {
      weekEnumable,
      dayEnum,
      modeEnum,
      booleanEnum,
      subject: '礼券发放',
      rootRoute: 'workbench',
      routeName: 'couponGrant',
      mode: 'add',
      isLoaded: false,
      id: null,
      /* Form */
      form: null,
      /* Popup */
      showAddFood: false,
      // DataTransfer
      transferRules: [],
      //FormRules
      rules: [],
      lock: false, // throttle lock

      /* extra data */
      channelTypeEnum,
      cycleTypeEnum,
      couponTypeEnum,
      showCouponPopup: false,
      type: 1,
      foodList: [],
      foodCategoryList: [],
      FoodCouponList: [],
      UserList: [],
      popPageNum: 1,
      /* extra form rule */
      rule2: [],
      transferRule2: []
      /* extra transfer */
    };
  },

  methods: {
    onBlurEvent(e) {
      this.formBlur(e, this);
    },

    async getData() {
      this.form = (await GetFoodCouponById(this.id)).data;
    },

    async getOtherData() {
      //
      if (this.id == 1) {
        this.form.couponCode = (await genCouponCode()).data;
      }
    },

    async insertData() {
      return AddFoodCoupon(this.form);
    },

    async delData() {
      return await DelFoodCouponById(this.id);
    },

    async editData() {
      return await EditFoodCoupon(this.form);
    },

    async btnDelClick() {
      await this.formDelete(this);
    },

    btnEditOrSaveSubmitClick: async function () {
      if (this.form.couponId == 0 || this.form.couponId == null) {
        utoast('请选择优惠券~', toastIconEnum.error);
        return;
      }

      if (this.form.userId == 0 || this.form.userId == null) {
        utoast('请选择会员~', toastIconEnum.error);
        return;
      }

      if (this.id == 2) {
        this.form = transfer(this.form, this.transferRules);
        let isOk = checker.check(this.form, this.rules);
        if (!isOk) {
          await utoast(checker.error, toastIconEnum.none);
          return;
        }
      }

      if (this.lock) {
        return;
      }

      if (!(await umodal('确认要提交吗？'))) {
        return;
      }
      const fn = this.id == 1 ? AddFoodCouponUser : BatchCreateCouponUser;
      const res = await fn(this.form);

      if (res?.code == 0) {
        await utoast('操作成功');
        setTimeout(() => {
          uNavigateTo(`/pages/${this.rootRoute}/${this.routeName}/list`);
        }, 1000);
      } else {
        setTimeout(() => {
          this.lock = false;
        }, 2000);
      }
    },

    /* Form Event */

    /* extra method */
    onChooseCoupon: function (type) {
      this.type = type;
      this.openCouponPopup();
    },

    closeCouponPopup: function () {
      this.showCouponPopup = !true;
    },

    openCouponPopup: async function () {
      this.showCouponPopup = true;
      const fn = this.type == 1 ? GetFoodCouponList : GetUserList;
      const {
        data: { list }
      } = await fn();
      this[this.type == 1 ? 'FoodCouponList' : 'UserList'] = list;
    },

    onItemClick: function (item) {
      this.type == 1
        ? ((this.form.couponId = item.id), (this.form.couponName = item.name), (this.form.typeId = item.typeId), (this.form.parValue = item.parValue))
        : ((this.form.userId = item.id), (this.form.userName = item.nickName));
      this.closeCouponPopup();
    },
    onPageChange: function (e) {
      this.popPageNum = e.pageNum;
    }
    //method put on the top
  }
};
</script>
<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';
</style>
